import { defineStore } from 'pinia'
import { reqLogin, reqLogout, reqUserInfo } from '@/api/user/index.ts'
import { constantRoute, asnycRoute, anyRoute } from '@/router/routes.ts'
import router from '@/router/index.ts'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
import cloneDeep from 'lodash/cloneDeep'
import { RouteRecordRaw } from 'vue-router'
import { reactive, ref } from 'vue'

const useUserStore = defineStore('userStore', () => {
  const token = ref(localStorage.getItem('TOKEN'))
  const userInfo = reactive<any>({
    avatar: '',
    name: '',
    menuRoute: [],
    routes: [],
    buttons: [],
  })
  /**
   * 登录
   * @param userInfo 用户信息
   */
  async function loginAction(userInfo: any) {
    if (!userInfo.password || !userInfo.username) {
      return Promise.reject(new Error('账号或密码为空'))
    }
    const result: any = await reqLogin(userInfo)
    if (result.code == 200) {
      // 登录成功 需要将token保存
      localStorage.setItem('TOKEN', result.data)
      token.value = result.data
      return 'ok'
    } else {
      return Promise.reject(new Error(result.message))
    }
  }

  /**
   * 获取登录后的用户信息
   */
  async function getUserInfo() {
    const respUserInfo: any = await reqUserInfo()
    if (respUserInfo.code === 200) {
      Object.assign(userInfo, respUserInfo.data)
      // 获取用户能够访问的异步路由数组
      let resultRoutes = filterUserRoutes(
        // 注意此处要深拷贝
        cloneDeep(asnycRoute),
        userInfo.routes,
      )
      resultRoutes = [...resultRoutes, anyRoute]
      // 动态添加路由
      resultRoutes.forEach((item: any) => {
        router.addRoute(item)
      })
      userInfo.menuRoute = [...constantRoute, ...resultRoutes]
    } else {
      return Promise.reject(new Error(respUserInfo.message))
    }
  }

  function filterUserRoutes(asnycUserRoute: any, routes: any) {
    return asnycUserRoute.filter((item: any) => {
      if (routes.includes(item.name)) {
        if (item.children && item.children.length > 0) {
          item.children = filterUserRoutes(item.children, routes)
        }
        return true
      }
    })
  }

  /**
   * 过滤不需要展示的菜单路由
   * @param routes 全部路由
   */
  function filterRoutes(routes: RouteRecordRaw[]): RouteRecordRaw[] {
    return routes.reduce((acc: RouteRecordRaw[], current) => {
      if (current.meta && current.meta.hidden === true) {
        return acc
      }

      const filteredChildren =
        (current.children || []).length > 0
          ? filterRoutes(current.children as RouteRecordRaw[])
          : []

      if (filteredChildren.length > 0) {
        current.children = filteredChildren
      } else {
        delete current.children
      }

      acc.push(current)
      return acc
    }, [])
  }

  async function logout() {
    const result = await reqLogout()
    if (result.code === 200) {
      localStorage.removeItem('TOKEN')
      token.value = ''
      Object.assign(userInfo, {
        avatar: '',
        name: '',
      })
      location.reload()
      return 'ok'
    } else {
      return Promise.reject(new Error(result.message))
    }
  }

  return { token, loginAction, filterRoutes, getUserInfo, userInfo, logout }
})

export default useUserStore
